<template>
  <el-dialog
    title="修改属性"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      size="mini"
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <el-form-item label="分组属性名称">
        {{ dataForm.name }}
      </el-form-item>

      <el-form-item label="分配属性" prop="attrIds">
        <el-select
          multiple
          filterable
          v-model="dataForm.attrIds"
          style="width: 100%"
        >
          <el-option
            v-for="item in attrArrays"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  addOrUpdateAttrGroupAttr,
  getAttrByAttrGroupId,
  productAttrList,
} from "@/api/product";
export default {
  data() {
    return {
      attrArrays: [],
      addOrUpdateVisible: false,
      visible: false,
      dataListLoading: false,
      dataForm: {
        id: 0,
        attrIds: [],
        name: "",
      },
      dataRule: {},
    };
  },
  components: {},

  activated() {},
  methods: {
    productAttrList() {
      // 规格参数才会有分组
      productAttrList({ type: 1 }).then((res) => {
        if (res && res.code === 0) {
          this.attrArrays = res.data;
        }
      });
    },
    getAttrByAttrGroupId() {
      getAttrByAttrGroupId(this.dataForm.id).then((res) => {
        if (res && res.code === 0) {
          this.dataForm.attrIds = res.data;
        }
      });
    },
    init(data) {
      this.visible = true;
      this.dataForm.id = data.id;
      this.dataForm.name = data.name;
      this.productAttrList();
      this.$nextTick(() => {
        this.getAttrByAttrGroupId();
        this.$refs["dataForm"].resetFields();
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addOrUpdateAttrGroupAttr({
            groupId: this.dataForm.id || "",
            attrIds: this.dataForm.attrIds,
          }).then((res) => {
            if (res && res.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
  },
};
</script>
